﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExpertMIS.Brokers;
using ExpertMIS.Entities;
using System.Text;
using System.Reflection;
using ExpertMIS.Codes;
using System.Collections;

namespace ExpertMIS.Forums.UserControl
{
    public partial class ucPostQuestion : System.Web.UI.UserControl
    {
        #region Fields

        private string _currentDomain = string.Empty;
        private IList<DomainEntity> _expertGoodAtDomains = null;
        private DomainBroker _domainBroker = new DomainBroker();

        #endregion

        #region Events

        public event EventHandler OnPostSuccess;

        #endregion

        private bool FAQ
        {
            get
            {
                return ViewState["_IS_FAQ_"] != null && (bool)ViewState["_IS_FAQ_"];
            }
            set
            {
                ViewState["_IS_FAQ_"] = value;
            }
        }

        private void PostNewQuestion()
        {
            QuestionBroker questionBroker = new QuestionBroker();
            QuestionEntity question = questionBroker.NewEntity() as QuestionEntity;

            question.Title = txTitle.Text;
            question.Context = txContent.Text;
            question.ClientIP = ExpertMIS.Codes.Utility.GetClientIP();
            question.UserOID = Utility.GetEnvironment().GetCurrentUser().OID;
            if (FAQ)
            {
                question.Status = QuestionStatus.Accepted;
            }
            else
            {
                question.Status = QuestionStatus.UnPassed;
            }
            question.FAQ = FAQ;

            string[] splitted = string.IsNullOrEmpty(Request["txDomains"]) ? new string[0] : Request["txDomains"].Split(',');
            List<string> domainList = new List<string>();
            foreach (string s in splitted)
            {
                domainList.Add(s);
            }

            splitted = string.IsNullOrEmpty(Request["txExperts"]) ? new string[0] : Request["txExperts"].Split(',');
            List<string> expertList = new List<string>();
            foreach (string s in splitted)
            {
                expertList.Add(s);
            }

            Hashtable htPosts = new Hashtable();
            htPosts.Add("domains", domainList);
            htPosts.Add("experts", expertList);

            if (questionBroker.SaveEntity(question, htPosts).Code == 0)
            {
                if (OnPostSuccess == null)
                {
                    Response.Redirect(ResolveClientUrl("~/Forums/PostSuccessed.aspx?oid=" + question.OID));
                }
                else
                {
                    OnPostSuccess(this, null);
                }
            }
        }

        protected string GetCurrentUserInfo(string field)
        {
            SYS.Common.RMSIntf.ISYSUser user = ExpertMIS.Codes.Utility.GetEnvironment().GetCurrentUser();

            if (user != null)
            {
                PropertyInfo pInfo = user.GetType().GetProperty(field);
                if (pInfo != null)
                {
                    object o = pInfo.GetValue(user, null);
                    return o != null ? o.ToString() : "";
                }
            }

            return "";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            RefreshDomain();

            int minLength = 4;
            int.TryParse(Utility.GetEnvironmentValue("titleminlength"), out minLength);
            txTitle.Attributes["minlength"] = minLength.ToString();
        }

        protected void RefreshDomain()
        {
            if (dlDomains.DataSource == null)
            {
                IList<DomainEntity> list = _domainBroker.GetAllDomains();

                dlDomains.DataSource = list;
                dlDomains.DataBind();
            }
        }

        private void OnChildItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                CheckBox chkDomain = e.Item.FindControl("chkDomain") as CheckBox;
                DomainEntity childComain = e.Item.DataItem as DomainEntity;
                if (chkDomain != null)
                {
                    chkDomain.Attributes.Add("domain", childComain.OID);
                    chkDomain.Attributes.Add("parentdomain", _currentDomain);
                }

                if (_expertGoodAtDomains != null && chkDomain != null)
                {
                    foreach (DomainEntity domain in _expertGoodAtDomains)
                    {
                        if (domain.OID.Equals(_currentDomain))
                        {
                            chkDomain.Checked = true;
                            break;
                        }
                    }
                }
            }
        }

        protected void dlDomains_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataList dlChilds = e.Item.FindControl("dlChilds") as DataList;
                CheckBox chkDomainRoot = e.Item.FindControl("chkDomainRoot") as CheckBox;
                DomainEntity entity = e.Item.DataItem as DomainEntity;
                if (dlChilds != null && entity != null)
                {
                    _currentDomain = entity.OID;
                    dlChilds.ItemDataBound += new DataListItemEventHandler(OnChildItemDataBound);
                    dlChilds.DataSource = _domainBroker.GetChildDomain(entity.OID);
                    dlChilds.DataBind();

                    if (_expertGoodAtDomains != null && chkDomainRoot != null)
                    {
                        foreach (DomainEntity domain in _expertGoodAtDomains)
                        {
                            if (domain.OID.Equals(_currentDomain))
                            {
                                chkDomainRoot.Checked = true;
                                break;
                            }
                        }
                    }
                }
            }
        }

        protected void btnPost_Click(object sender, ImageClickEventArgs e)
        {
            PostNewQuestion();
        }

        public void PostFAQ(string ExpertOID)
        {
            trAskForExpert.Visible = false;

            _expertGoodAtDomains = _domainBroker.GetExpertGoodAtDomains(ExpertOID);
            FAQ = true;
        }

        public void SetContentHeight(int newHeight)
        {
            tdQuestionContent.Style["height"] = string.Format("{0}px", newHeight);
            txContent.Height = new Unit(newHeight);
        }
    }
}